<template>
  <div class="text" :style="computedStyle">
    {{ timestr }}
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import type { CSSProperties } from 'vue'
import dayjs from 'dayjs'

// Props
const props = defineProps<{
  widgetOptions: any
  isPreview?: Boolean
}>()

const emit = defineEmits([])

const setupOption = computed(() => {
  return props.widgetOptions.setup
})

const timestr = ref<string>(dayjs().format('YYYY-MM-DD HH:mm:ss'))

// 计算样式
const computedStyle = computed<CSSProperties>(() => ({
  color: setupOption.value.color,
  fontWeight: setupOption.value.fontWeight,
  fontSize: `${setupOption.value.fontSize}px`,
  letterSpacing: `${setupOption.value.letterSpacing}em`,
  backgroundColor: setupOption.value.backgroundColor,
  textAlign: setupOption.value.textAlign,
  whiteSpace: setupOption.value.whiteSpace ? 'pre-line' : 'normal'
}))

// 时间格式处理函数
function check(val: number): string {
  return val < 10 ? '0' + val : String(val)
}

function formatFunction(date: Date, fmt: string): string {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  const o: Record<string, number> = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
    'q+': Math.floor((date.getMonth() + 3) / 3),
    S: date.getMilliseconds()
  }
  for (const k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? String(o[k]) : ('00' + o[k]).substr(String(o[k]).length)
      )
    }
  }
  return fmt
}

function formatWeek(date: Date, fmt: string): string {
  const year = date.getFullYear()
  const month = check(date.getMonth() + 1)
  const day = check(date.getDate())
  const hours = check(date.getHours())
  const minutes = check(date.getMinutes())
  const seconds = check(date.getSeconds())
  const dayCycleArray = ['日', '一', '二', '三', '四', '五', '六']
  const week = ` 星期${dayCycleArray[date.getDay()]}`

  if (fmt === 'year-week') {
    return `${year}-${month}-${day}${week}`
  } else if (fmt === 'year-h-m-week') {
    return `${year}-${month}-${day} ${hours}:${minutes}${week}`
  } else if (fmt === 'year-h-m-s-week') {
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}${week}`
  } else if (fmt === 'week') {
    return week
  }
  return ''
}

function displayTime() {
  const format = setupOption.value.timeFormat || 'yyyy-MM-dd hh:mm:ss'
  timestr.value = format.includes('week')
    ? formatWeek(new Date(), format)
    : formatFunction(new Date(), format)
}

function getTime() {
  setInterval(displayTime, 1000)
}

onMounted(() => {
  getTime()
})
</script>

<style scoped lang="scss">
.text {
  width: 100% !important;
  height: 100% !important;
  overflow: hidden;
}
</style>
